<?php
/**
 * 账号登录控制器
 */

namespace Apps\Acp\Controllers;


use Apps\Acp\Models\Manager;
use Apps\Common\Constant\AcpConstant;
use Apps\Common\Controller\AcpBaseController;
use Deyi\Functions\CaptchaFunction;
use Deyi\Functions\ObjectFunction;
use Deyi\Functions\UtilFunction;

class AccountController extends AcpBaseController
{
    const CATPCHA_SESSION_KEY = '_acp_u_c';

    public function loginAction()
    {
        $this->checkLogin();
    }

    public function logoutAction()
    {
        $this->view->disable();
        $this->session->destroy();

        $this->redirectToUrl('/acp/login');
    }

    public function loggingAction()
    {
        $userName = $this->getParamValue('username', null, null, false, '', true);
        $passWord = $this->getParamValue('password', null, null, false, '', true);
        $captcha = $this->getParamValue('captcha', null, null, false, '', true);
        $captchaText = $this->session->get(self::CATPCHA_SESSION_KEY);

        $res = Manager::getInstance()->getOneByField('username', $userName);

        if (!$res) {
            $this->flashSession->error('账号不存在');
            $this->redirectToUrl('/acp/login');
        }

        if ($captcha !== $captchaText) {
            $this->flashSession->error('验证码不正确');
            $this->redirectToUrl('/acp/login');
        }

        if (!$res->enable) {
            $this->flashSession->error('账号已被关闭');
            $this->redirectToUrl('/acp/login');
        }

        if (md5(md5($passWord) . $res->salt) !== $res->password) {
            $this->flashSession->error('密码不正确');
            static::$_logger->error('后台密码输入错误,来路IP:' . UtilFunction::getClientIp());
            $this->redirectToUrl('/acp/login');
        }

        $this->session->set(
            AcpConstant::MANAGER_SESSION,
            ObjectFunction::toAo($res, Manager::getPropByTableName(Manager::getTableName()))
        );

        $this->redirectToUrl('/acp/');
    }

    public function captchaAction()
    {

        $captcha = new CaptchaFunction();
        $captcha->scale = 3;
        $captcha->createImage();
        $this->session->set(self::CATPCHA_SESSION_KEY, $captcha->getText());
        $captcha->outPut();
    }
}